#include "stdafx.h"
#include "hex.h"

/*static inline*/ int hex_value(TCHAR x)
{
	//if(x.length()<= 0)return -1;
	//x = uppercase(x);
	//std::transform(x.begin(), x.end(), x.begin(), ::toupper);

	if(x>='0' && x<='9') return x-'0';
	else if(x>='A' && x<='F') return x-'A'+0xA;
	else if(x>='a' && x<='f') return x-'a'+0xA;

	return -1;
}

/*static inline*/ int hex_value(GString& x)
{
	return hex_value(x[0]);
}

/*static inline*/ bool is_hex(_tstring x)
{
	for(int i = 0; i<(int)x.length(); i++)
	{
		if(hex_value(x[i]) == -1)
			return false;
	}
	return true;
}

//takes int or unsigned character
//returns hex value of character
/*static inline*/ _tstring hex_char(int c)
{
	_tstring a;
	TCHAR cBuf[6];

	_stprintf(cBuf, _T("%02X "), c&0xFF); 
	//a = (string) cBuf;
	a += cBuf[0];
	a += cBuf[1];
	return a.substr(0,2);
}

//takes hex string
//returns decimal value of hex string
//takes start, end, buffer, filestream
//returns dumps hex from start to end into buffer
void hex_dump(fstream& fs, std::vector<_tstring>& data, long start, long end)
{
	unsigned char c;
	int i = start;
	fs.seekg(start,ios::beg);
	while (!fs.eof() && i != end)
	{
		c = fs.get();
		data.push_back(hex_char(c));
		i++;
	}
}

//takes start, end, buffer, filestream
//returns replaces hex from start to end into file from buffer
void hex_overwrite(fstream& fs, std::vector<_tstring>& data, long start, long end)
{
	int i = start;
	int j = 0;
	fs.seekg(start,ios::beg);
	while (!fs.eof() && i != end && j < (int)data.size())
	{
		fs.put((unsigned char) (char_hex(data[j])));
		i++;
		j++;
	}
}
